package org.hepeng.fabric.gateway.pool.spring;

import org.apache.commons.pool2.impl.AbandonedConfig;
import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig;
import org.hepeng.fabric.gateway.pool.FabricGatewayObject;
import org.hepeng.fabric.gateway.pool.FabricGatewayObjectFactory;
import org.hepeng.fabric.gateway.pool.GatewayKey;
import org.hepeng.fabric.gateway.pool.GatewayKeyProvider;
import org.hepeng.fabric.gateway.pool.channel.GRpcChannelProperties;
import org.hepeng.fabric.gateway.pool.spring.interceptor.FabricGatewayInterceptor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author he peng
 * @date 2022/3/24
 */

@Configuration
@ConditionalOnProperty(prefix = "hyperledger.fabric.gateway.channel" , name = {"endpoint" , "tlsCertPem"})
@EnableConfigurationProperties(GRpcChannelProperties.class)
public class FabricGatewayPoolConfiguration {



    @Bean
    public GenericKeyedObjectPool<GatewayKey , FabricGatewayObject> gatewayPool(
            GRpcChannelProperties gRpcChannelProperties , GenericKeyedObjectPoolConfig<FabricGatewayObject> poolConfig , AbandonedConfig abandonedConfig) {

        return new GenericKeyedObjectPool<>(new FabricGatewayObjectFactory(gRpcChannelProperties), poolConfig, abandonedConfig);
    }


    @Bean
    public FabricGatewayInterceptor fabricGatewayInterceptor(GatewayKeyProvider keyProvider) {
        return new FabricGatewayInterceptor(keyProvider);
    }


    @Bean
    public WebMvcConfigurer fabricGatewayInterceptorConfigurer(FabricGatewayInterceptor interceptor) {
        return new WebMvcConfigurer() {

            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(interceptor);
            }

        };
    }
}
